angular.module('Pound')
    .controller('Pound.PoundCtrl', ['$scope', '$state', '$http', '$interval', '$ionicLoading', '$ionicPopup', '$stateParams', 'Http', 'imanDialog', 'Device', 'User', 'DevicePort', 'Help',
        function($scope, $state, $http, $interval, $ionicLoading, $ionicPopup, $stateParams, Http, imanDialog, Device, User, DevicePort, Help) {
            $scope.data = {
                Barcode: '',
                Weight: [],
                areaFlag: true,
                photo: User.get('Image')
            };

            var toast, t;

            $scope.imgPath = {
                weight: u9ImHd.getFullPath('/img/weight.png', 'Pound')
            };
            $scope.showToast = function(styleMes) {
                if (toast) {
                    toast.hide();
                }
                toast = imanDialog.toast({
                    message: styleMes,
                    block: true,
                    position: 'top',
                    duration: false,
                    backdropClickToClose: false,
                    hardwareBackButtonClose: false
                });
            };

            $scope.hideToast = function() {
                if (toast) {
                    toast.hide();
                    toast = null;
                }
            };

            /**
             * 进入页面前加载资源
             */
            $scope.$on('$ionicView.afterEnter', function() {
                $scope.showToast('请扫描单品信息');
                barcodePort();
                //getQcInfo('0006467478');
            });

            /**
             * 监听串口数据
             */
            $scope.$on('devicePort.DataReceived', function(e, barcode) {
                if ($scope.data.areaFlag) {
                    $scope.data.Barcode = barcode;
                    getQcInfo(barcode);
                } else {
                    if (barcode.length < 24) {
                        return;
                    }
                    var dataStr = parseData(barcode, '2C', '0D0A');
                    if ($scope.data.Weight[0]) {
                        $scope.data.Weight[0].NormValue = Number(dataStr[1]);
                        //获取数据立马关闭端口
                        DevicePort.close();
                        t = $interval(function() {
                            $scope.saveParam();
                        }, 3000);
                    }
                    $scope.$apply();
                }
            });
            /**
             * 离开页面时,销毁必要
             *
             */
            $scope.$on('$ionicView.beforeLeave', function() {
                DevicePort.close();
                if (toast) {
                    toast.hide();
                    toast = null;
                }
                $interval.cancel(t);
            });

            /**
             * 保存提交
             * @param type
             */
            $scope.saveParam = function() {
                if ($scope.data.Barcode === '') {
                    imanDialog.toastBottom('请扫描球拍信息！');
                    return;
                }
                if (!$scope.data.Weight[0] || !$scope.data.Weight[0].NormValue) {
                    imanDialog.toastBottom('重量值不能为空！');
                    return;
                }
                $ionicLoading.show();
                var realUser, realWorkLocation, realWorkLocationName;
                /**
                 * 判断独立称重和非独立称重(独立称重请看相关文档)
                 */
                if ($scope.data.barcode.Work === Device.get().Work._id) {
                    realUser = $scope.data.Users;
                    realWorkLocation = $scope.data.barcode.WorkLocation;
                    realWorkLocationName = $scope.data.barcode.WorkLocationName;
                } else {
                    realUser = [User.get()._id];
                    realWorkLocation = Device.get().WorkLocation._id;
                    realWorkLocationName = Device.get().WorkLocation.Name;
                }
                Http.post({
                    url: '/api/Wrapper/setWrapperMeasure',
                    data: {
                        Parameter: {
                            Barcode: $scope.data.Barcode,
                            TerminalUniqueID: Device.getUUID(),
                            Work: Device.get().Work._id || 0,
                            WorkName: Device.get().Work.Name || '',
                            realWorkLocation: realWorkLocation || '',
                            realWorkLocationName: realWorkLocationName || '',
                            Users: realUser,
                            QCRecords: $scope.data.Weight
                        }
                    }
                }).then(function() {
                    $ionicLoading.hide();
                    //$state.go('Pound');
                    resetInfo();
                    imanDialog.toastCenter('提交成功');
                    DevicePort.close();
                    barcodePort();
                })['finally'](function() {
                    $ionicLoading.hide();
                });
            };

            /**
             * 处理服务器的响应
             * @param Barcode
             */
            function getQcInfo(Barcode) {
                if (!Barcode) {
                    return;
                }
                $ionicLoading.show();
                Http.post({
                    url: '/api/Wrapper/getWrapperInfo',
                    data: {
                        Parameter: {
                            Barcode: Barcode,
                            TerminalUniqueID: Device.getUUID(),
                            HDWork: Device.get().Work
                        }
                    }
                }).then(function(info) {
                    if (info.basicInfo.MOCode) {
                        $scope.hideToast();
                    }
                    angular.forEach(info.qcStandard, function(obj) {
                        if (obj.QCCode.indexOf('ZL') > -1) {
                            $scope.data.Weight.push(obj);
                        }
                    });
                    $scope.data.barcode = info.basicInfo;
                    $scope.data.Users = info.basicInfo.Users;
                    //扫描完单品信息,关闭RFID端口,同时打开称重端口
                    DevicePort.close();
                    poundPort();
                    // t = $interval(function() {
                    //         $scope.saveParam();
                    //     }, 9000);
                })['finally'](function() {
                    $ionicLoading.hide();
                });
            }

            /**
             * 解析串口数据
             * @param data 需要解析的数据
             * @param parse 分隔符号
             * @param endMark 结束符号
             * @returns {*}
             */
            function parseData(data, parse, endMark) {
                var dataSplit = data.split(parse);
                if (dataSplit.length < 3) {
                    return null;
                }
                var temp = dataSplit[2].replace(endMark, '');
                if (temp.length < 24) {
                    return null;
                }
                var tempSplit = [];
                tempSplit.push(temp.substr(0, 2));
                tempSplit.push(temp.substr(2, 14).replace(/20/g, ''));
                tempSplit.push(temp.substr(16, 8).replace(/20/g, ''));
                var result = [];
                for (var i = 0; i < tempSplit.length; i++) {
                    var t = tempSplit[i],
                        r = '';
                    for (var j = 0; j < t.length; j += 2) {
                        r += String.fromCharCode(parseInt(t.substr(j, 2), 16));
                    }
                    result.push(r);
                }
                return result;
            }

            /**
             * [goCircumference 跳转到周径测量页面]
             * 
             */
            $scope.goCircumference = function() {
                Help.loadApp('Circumference').then(function() {
                    DevicePort.close();
                    if (toast) {
                        toast.hide();
                        toast = null;
                    }
                    $state.go('Circumference', {
                        Barcode: $scope.data.Barcode
                    });
                }, function() {
                    imanDialog.toastBottom('进入周径测量应用失败，请确认是否已正确安装然后重试。');
                });
            };

            $scope.init = function() {
                getQcInfo($stateParams.Barcode);
            };

            $scope.init();

            function barcodePort() {
                DevicePort.open({
                    device: 0,
                    baudrate: 115200,
                    parseFn: true
                }).then(function() {
                    $scope.data.areaFlag = true;
                    imanDialog.toastBottom("扫描单品信息端口打开成功！");
                }, function(err) {
                    imanDialog.toastBottom(err);
                });
            }

            function poundPort() {
                DevicePort.open({
                    device: 1,
                    parser: '0D0A'
                }).then(function() {
                    $scope.data.areaFlag = false;
                    imanDialog.toastBottom("称重端口打开成功");
                }, function() {
                    imanDialog.toastBottom('称重端口打开失败');
                });
            }

            function resetInfo() {
                $scope.data.Barcode = '';
                $scope.data.barcode = {};
                $scope.data.Users = {};
                $scope.data.Weight = [];
                if (toast) {
                    toast.hide();
                    toast = null;
                }
                $interval.cancel(t);
                $scope.showToast('请扫描单品信息');
            }
        }
    ]);
